using System;
using System.Collections.Generic;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace LibraryManagementSystem
{
    public partial class BookDetailForm : Form
    {
        private readonly BookService _bookService;
        private Book _book;
        private readonly List<BookCategory> _categories;
        private bool _isNewBook;
        private string _defaultStatus = "在馆"; // 默认状态

        public BookDetailForm(Book book, List<BookCategory> categories)
        {
            InitializeComponent();
            _bookService = new BookService();
            _categories = categories;
            _book = book;
            _isNewBook = book == null;

            if (_isNewBook)
            {
                this.Text = "添加新图书";
                _book = new Book();
            }
            else
            {
                this.Text = $"编辑图书 - {book.Title}";
            }
        }

        private void BookDetailForm_Load(object sender, EventArgs e)
        {
            // 设置分类下拉框
            cmbCategory.Items.Clear();
            foreach (var category in _categories)
            {
                cmbCategory.Items.Add(new ComboBoxItem { Text = category.CategoryName, Value = category.Id });
            }
            cmbCategory.DisplayMember = "Text";
            cmbCategory.ValueMember = "Value";
            
            // 隐藏不需要的控件
            cmbStatus.Visible = false;
      

            // 确保状态标签是可见的
            label12.Visible = true;
            label12.Text = "状态：";

            // 创建状态单选按钮组
            GroupBox grpStatus = new GroupBox();
            grpStatus.Text = "";  // 不需要标题，因为已经有标签
            grpStatus.Location = cmbStatus.Location;
            grpStatus.Size = new System.Drawing.Size(300, 40);  // 减小高度，更适合界面
            this.Controls.Add(grpStatus);

            // 在一行中均匀分布四个单选按钮
            int buttonWidth = 65;
            int spacing = 10;
            
            RadioButton rdbInLibrary = new RadioButton();
            rdbInLibrary.Text = "在馆";
            rdbInLibrary.Location = new System.Drawing.Point(10, 12);
            rdbInLibrary.Size = new System.Drawing.Size(buttonWidth, 20);
            rdbInLibrary.Tag = "在馆";
            rdbInLibrary.Checked = true;
            grpStatus.Controls.Add(rdbInLibrary);

            RadioButton rdbBorrowed = new RadioButton();
            rdbBorrowed.Text = "借出";
            rdbBorrowed.Location = new System.Drawing.Point(10 + buttonWidth + spacing, 12);
            rdbBorrowed.Size = new System.Drawing.Size(buttonWidth, 20);
            rdbBorrowed.Tag = "借出";
            grpStatus.Controls.Add(rdbBorrowed);

            RadioButton rdbReserved = new RadioButton();
            rdbReserved.Text = "预约";
            rdbReserved.Location = new System.Drawing.Point(10 + (buttonWidth + spacing) * 2, 12);
            rdbReserved.Size = new System.Drawing.Size(buttonWidth, 20);
            rdbReserved.Tag = "预约";
            grpStatus.Controls.Add(rdbReserved);

            RadioButton rdbMaintenance = new RadioButton();
            rdbMaintenance.Text = "维修";
            rdbMaintenance.Location = new System.Drawing.Point(10 + (buttonWidth + spacing) * 3, 12);
            rdbMaintenance.Size = new System.Drawing.Size(buttonWidth, 20);
            rdbMaintenance.Tag = "维修";
            grpStatus.Controls.Add(rdbMaintenance);

            // 如果是编辑模式，填充表单
            if (!_isNewBook)
            {
                txtISBN.Text = _book.ISBN;
                txtTitle.Text = _book.Title;
                txtAuthor.Text = _book.Author;
                txtPublisher.Text = _book.Publisher;
                dtpPublishDate.Value = _book.PublishDate ?? DateTime.Now;
                chkNoPublishDate.Checked = !_book.PublishDate.HasValue;
                
                // 设置分类
                foreach (ComboBoxItem item in cmbCategory.Items)
                {
                    if ((int)item.Value == _book.CategoryId)
                    {
                        cmbCategory.SelectedItem = item;
                        break;
                    }
                }
                
                nudPrice.Value = _book.Price ?? 0;
                nudPages.Value = _book.Pages ?? 0;
                txtDescription.Text = _book.Description;
                txtLocation.Text = _book.Location;
                txtCoverImage.Text = _book.CoverImage;
                
                // 设置状态单选按钮
                if (_book.Status != null)
                {
                    foreach (RadioButton rdb in grpStatus.Controls)
                    {
                        if (rdb.Tag.ToString() == _book.Status)
                        {
                            rdb.Checked = true;
                            break;
                        }
                    }
                }
            }
            else
            {
                dtpPublishDate.Value = DateTime.Now;
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            // 验证输入
            if (string.IsNullOrEmpty(txtISBN.Text) || string.IsNullOrEmpty(txtTitle.Text) ||
                string.IsNullOrEmpty(txtAuthor.Text) || string.IsNullOrEmpty(txtPublisher.Text) ||
                cmbCategory.SelectedItem == null)
            {
                MessageBox.Show("请填写所有必填字段", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            // 检查ISBN是否已存在
            int currentBookId = _isNewBook ? 0 : _book.Id;
            if (_bookService.IsIsbnExists(txtISBN.Text.Trim(), currentBookId))
            {
                MessageBox.Show($"ISBN '{txtISBN.Text.Trim()}' 已存在，请修改后重试", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtISBN.Focus();
                return;
            }

            // 更新图书对象
            _book.ISBN = txtISBN.Text.Trim();
            _book.Title = txtTitle.Text.Trim();
            _book.Author = txtAuthor.Text.Trim();
            _book.Publisher = txtPublisher.Text.Trim();
            _book.PublishDate = chkNoPublishDate.Checked ? null : (DateTime?)dtpPublishDate.Value;
            _book.CategoryId = (int)((ComboBoxItem)cmbCategory.SelectedItem).Value;
            _book.Price = nudPrice.Value > 0 ? nudPrice.Value : (decimal?)null;
            _book.Pages = (int)nudPages.Value > 0 ? (int)nudPages.Value : (int?)null;
            _book.Description = txtDescription.Text.Trim();
            _book.Location = txtLocation.Text.Trim();
            _book.CoverImage = txtCoverImage.Text.Trim();
            
            // 获取选中的状态单选按钮
            foreach (Control ctrl in this.Controls)
            {
                if (ctrl is GroupBox grp && ctrl.Location == cmbStatus.Location)
                {
                    foreach (RadioButton rdb in grp.Controls)
                    {
                        if (rdb.Checked)
                        {
                            _book.Status = rdb.Tag.ToString();
                            break;
                        }
                    }
                    break;
                }
            }

            bool success;
            try
            {
                if (_isNewBook)
                {
                    // 添加新图书
                    int id = _bookService.AddBook(_book);
                    success = id > 0;
                    _book.Id = id;
                }
                else
                {
                    // 更新现有图书
                    success = _bookService.UpdateBook(_book);
                }

                if (success)
                {
                    MessageBox.Show(_isNewBook ? "图书添加成功" : "图书更新成功", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
                else
                {
                    MessageBox.Show(_isNewBook ? "添加图书失败" : "更新图书失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (MySql.Data.MySqlClient.MySqlException ex)
            {
                if (ex.Message.Contains("Duplicate entry") && ex.Message.Contains("ISBN"))
                {
                    MessageBox.Show($"ISBN '{_book.ISBN}' 已存在，请修改后重试", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtISBN.Focus();
                }
                else
                {
                    MessageBox.Show($"数据库错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        private void chkNoPublishDate_CheckedChanged(object sender, EventArgs e)
        {
            dtpPublishDate.Enabled = !chkNoPublishDate.Checked;
        }

        private void btnBrowseImage_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog dialog = new OpenFileDialog())
            {
                dialog.Filter = "图片文件|*.jpg;*.jpeg;*.png;*.gif;*.bmp|所有文件|*.*";
                dialog.Title = "选择图书封面图片";

                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    txtCoverImage.Text = dialog.FileName;
                }
            }
        }

        private void chkUpdateItems_CheckedChanged(object sender, EventArgs e)
        {
         ;
        }
    }
} 